package com.xufx.thread.liaoxuefeng.thread18_ForkJoin;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * Created by xufx on 2022/1/5 23:07
 * Fork/Join线程池，可以执行一种特殊的任务，把一个大任务拆分成多个小任务并行执行
 * Fork/Join任务的原理：判断一个任务是否足够小，如果是，直接计算；如果不是，分拆成几个小任务分别计算
 * Fork/Join数据库在Java标准库的很多场合中都有使用
 */
public class Main {
    public static void main(String[] args) {
        // 创建2000个随机数组成的数组
        long[] array = new long[2000];
        long expectedSum = 0;
        for (int i = 0; i < array.length; i++){
            array[i] = random();
            expectedSum += array[i];
        }
        System.out.println("Sum: " + expectedSum);

        ForkJoinTask<Long> task = new SumTask(array, 0, array.length);
        Long startTime = System.currentTimeMillis();
        Long result = ForkJoinPool.commonPool().invoke(task);
        Long endTime = System.currentTimeMillis();
        System.out.println("invoke time: " + (endTime - startTime) + "ms");
    }

    static Random random = new Random(0);
    static long random(){
        return random.nextInt(10000);
    }
}

class SumTask extends RecursiveTask<Long>{
    static final int THRESHOLD = 500;
    long[] array;
    int start;
    int end;

    SumTask(long[] array, int start, int end){
        this.array = array;
        this.start = start;
        this.end   = end;
    }

    @Override
    protected Long compute(){
        if (end - start <= THRESHOLD){
            long sum = 0;
            for (int i = start; i < end; i++){
                sum += this.array[i];
                try {
                    Thread.sleep(1);
                }catch (Exception e){

                }
            }
            return sum;
        }
        // 如果任务太大，就要分
        int middle = (end + start) / 2;
        SumTask sumTask1 = new SumTask(this.array, start, middle);
        SumTask sumTask2 = new SumTask(this.array, middle, end);
        invokeAll(sumTask1, sumTask2);
        Long subresult1 = sumTask1.join();
        Long subresult2 = sumTask2.join();
        Long result = subresult1 + subresult2;
        return result;
    }
}